$(function () {

    function getBook() {
        $.get('http://www.liulongbin.top:3006/api/getbooks', function (res) {
            if (res.status !== 200) return alert('获取图书失败')
            var rows = []
            $.each(res.data, function (i, item) {
                rows.push('<tr><td>' + item.id + '</td><td>' + item.bookname + '</td><td>' + item.author + '</td><td>' + item.publisher + '</td><td><a href="javascript:;" class="del" data-id="' + item.id + '">删除<a></td></tr>')
                $('#tb').empty().append(rows.join(''))
            })
        })

    }
    getBook()

    // 删除模块
    $('#tb').on('click', '.del', function () {
        var id = $(this).attr('data-id')
        $.get('http://www.liulongbin.top:3006/api/delbook', { id: id }, function (res) {
            if (res.status !== 200) return alert('删除图书失败')
            getBook()
        })

    })

    // 添加模块
    $('#btnAdd').on('click', function () {
        var bookname = $('#iptBookName').val().trim()
        var author = $('#iptAuthor').val().trim()
        var publisher = $('#iptpublisher').val().trim()
        if (bookname.length <= 0 || author.length <= 0 || publisher.length <= 0) return alert('输入的内容不能为空')
        $.post('http://www.liulongbin.top:3006/api/addbook', { bookname: bookname, author: author, publisher: publisher }, function (res) {
            if (res.status !== 201) return alert('添加图书失败')
            getBook()
        })
        $('#iptBookName').val('')
        $('#iptAuthor').val('')
        $('#iptpublisher').val('')
    })




})